//
//  FieldViewController.m
//  BigToBig
//
//  Created by 毛丽媛 on 16/8/31.
//  Copyright © 2016年 cn.cloudtp. All rights reserved.
//

#import "FieldViewController.h"

@interface FieldViewController ()<UIImagePickerControllerDelegate>
@property(nonatomic,strong)UIImageView *logoView;

@end

@implementation FieldViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.view.backgroundColor = [UIColor whiteColor];
    UILabel *titleLab = [[UILabel alloc]initWithFrame:CGRectMake(0, 0, 100, 40)];
    titleLab.text = self.titleName;
    titleLab.textColor = [UIColor whiteColor];
    [self setBackBar];
    titleLab.textAlignment = NSTextAlignmentCenter;
    self.navigationItem.titleView = titleLab;
    
    self.navigationController.navigationBar.translucent = NO;
    
    self.logoView = [[UIImageView alloc] initWithFrame:CGRectMake(kScreenWidth / 2 - 100, 100, 200, 200)];
    self.logoView.backgroundColor = [UIColor yellowColor];
    [self.view addSubview:self.logoView];
    
    UIButton *upLoad = [[UIButton alloc] initWithFrame:CGRectMake(30, self.logoView.maxY + 35, kScreenWidth - 60, 35)];

    upLoad.backgroundColor = [UIColor colorWithRed:0.337 green:0.541 blue:1.000 alpha:1.000];
    [upLoad setTitle:@"点击上传" forState:UIControlStateNormal];
    upLoad.layer.cornerRadius = 5;
    
    [upLoad addTarget:self action:@selector(upLogo) forControlEvents:UIControlEventTouchUpInside];
    
    [self.view addSubview:upLoad];
    
    UILabel *lab = [[UILabel alloc] initWithFrame:CGRectMake(30, 20, 200, 25)];
    lab.text = @"项目标志非企业标志";
    lab.textColor = [UIColor lightGrayColor];
    [self.view addSubview:lab];
    
    
}

- (void)upLogo{
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    
    if (status == NotReachable) {
        
        MBProgressHUD *HUD = [MBProgressHUD showHUDAddedTo:KeyWindow animated:YES];
        HUD.labelText = @"请联网后设置头像";
        HUD.mode = MBProgressHUDModeText;
        [HUD hide:YES afterDelay:1.0];
        
        return;
        
    }
    
    UIAlertController *alertController;
    
    __block NSUInteger blockSourceType = 0;
    
    // 判断是否支持相机因为模拟器不支持相机所以在模拟器上不会有相机这个选项
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera])
    {
        //支持访问相机与相册情况
        alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            //相册
            
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            
            imagePickerController.delegate = self;
            
            imagePickerController.allowsEditing = YES;
            
            imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }]];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
            NSLog(@"点击拍照");
            //相机
            
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            
            imagePickerController.delegate = self;
            
            imagePickerController.allowsEditing = YES;
            
            imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            [self presentViewController:imagePickerController animated:YES completion:nil];
        }]];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            NSLog(@"点击取消");
            // 取消
            return;
        }]];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
    else
    {
        //只支持访问相册情况
        alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"从相册中选取" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

            //相册
            blockSourceType = UIImagePickerControllerSourceTypePhotoLibrary;
            
            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            
            imagePickerController.delegate = self;
            
            imagePickerController.allowsEditing = YES;
            
            imagePickerController.sourceType = blockSourceType;
            
            [self presentViewController:imagePickerController animated:YES completion:^{
                
            }];
        }]];
        
        [alertController addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            
            //            NSLog(@"点击取消");
            // 取消
            return;
        }]];
        
        [self presentViewController:alertController animated:YES completion:nil];
    }
}

#pragma mark - 选择图片后,回调选择

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = [info objectForKey:UIImagePickerControllerEditedImage];
    
    /* 此处info 有六个可选类型
     * UIImagePickerControllerMediaType; // an NSString UTTypeImage)
     * UIImagePickerControllerOriginalImage;  // a UIImage 原始图片
     * UIImagePickerControllerEditedImage;    // a UIImage 裁剪后图片
     * UIImagePickerControllerCropRect;       // an NSValue (CGRect)
     * UIImagePickerControllerMediaURL;       // an NSURL
     * UIImagePickerControllerReferenceURL    // an NSURL that references an asset in the AssetsLibrary framework
     * UIImagePickerControllerMediaMetadata    // an NSDictionary containing metadata from a captured photo
     */
    
    self.logoView.image = image;
    
    //        NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    //        //把uidStr即用户的id作为key进行图片名称的存储这样能保证不同的用户取到的不同的图片
    ////        NSLog(@"%@",uidStr);
    //        [userDefaults setObject:self.imgName forKey:uidStr];
    //        [userDefaults synchronize];
//    NSUserDefaults *UserID = [NSUserDefaults standardUserDefaults];
//    NSString *UID = [UserID objectForKey:@"userID"];
//    
//    NSString *uidStr = [NSString stringWithFormat:@"%@",UID];
//    
//    NSString *str1 = [self md5HexDigest:uidStr];
//    
//    NSString *b = [str1 substringWithRange:NSMakeRange(8,16)];
//    NSString *str2 = @".png";
//    NSString *imgName = [NSString stringWithFormat:@"%@%@",b,str2];
    
//    [self saveImage:image withName:imgName];
}

//#pragma mark - 保存图片至本地沙盒
////#define boundary @"itcast-upload"
//
//- (NSString *)md5HexDigest:(NSString*)password
//{
//    const char *original_str = [password UTF8String];
//    unsigned char result[CC_MD5_DIGEST_LENGTH];
//    CC_MD5(original_str, strlen(original_str), result);
//    NSMutableString *hash = [NSMutableString string];
//    for (int i = 0; i < 16; i++)
//    {
//        [hash appendFormat:@"%02X", result[i]];
//    }
//    NSString *mdfiveString = [hash lowercaseString];
//    
//    NSLog(@"Encryption Result = %@",mdfiveString);
//    return mdfiveString;
//}
//- (void)saveImage:(UIImage *)currentImage withName:(NSString *)imageName
//{
//    
//    NSUserDefaults* userID = [NSUserDefaults standardUserDefaults];
//    NSString *Uid = [userID objectForKey:@"userID"];
//    NSString *uidStr = [NSString stringWithFormat:@"%@",Uid];
//    NSString *str1 = [self md5HexDigest:uidStr];
//    NSString *b = [str1 substringWithRange:NSMakeRange(8,16)];
//    NSString *str2 = @".png";
//    NSString *imgName = [NSString stringWithFormat:@"%@%@",b,str2];
//    self.imgName = imgName;
//    
//    NSLog(@"%@",imgName);
//    
//    NSData *imageData = UIImageJPEGRepresentation(currentImage, 0.8);
//    
//    [[AFHTTPSessionManager manager] POST:@"61.135.176.43:6080/picture/picture/head_portrait.json" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
//        
//        [formData appendPartWithFileData:imageData name:@"userfile" fileName:imgName mimeType:@"image/png"];
//        
//    } success:^(NSURLSessionDataTask *task, id responseObject) {
//        
//        NSLog(@"%@",responseObject);
//
//    } failure:^(NSURLSessionDataTask *task, NSError *error) {
//        
//        
//    }];
//    
//    // 获取沙盒目录
//    NSString *fullPath = [[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"] stringByAppendingPathComponent:imgName];
//    
//    // 将图片写入文件
//    [imageData writeToFile:fullPath atomically:NO];
//}

- (void)setBackBar{
    
    BackButton *backBtn=[BackButton buttonWithType:UIButtonTypeCustom];
    backBtn.frame = CGRectMake(0, 0, 20, 44);
    [backBtn addTarget:self action:@selector(backController) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    [backBtn.imageView setContentMode:UIViewContentModeLeft];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:backBtn];
    [self.navigationItem setHidesBackButton:YES animated:YES];
    
    BackButton *saveBtn=[BackButton buttonWithType:UIButtonTypeCustom];
    saveBtn.frame = CGRectMake(kScreenWidth - 44,0 , 44, 44);
    [saveBtn addTarget:self action:@selector(SaveMessage) forControlEvents:UIControlEventTouchUpInside];
    [saveBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveBtn setTitle:@"保存" forState:UIControlStateNormal];
    [saveBtn.imageView setContentMode:UIViewContentModeLeft];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:saveBtn];
    [self.navigationItem setHidesBackButton:YES animated:YES];
    
}

- (void)SaveMessage{
    
}

- (void)backController{
    
    [self.navigationController popViewControllerAnimated:YES];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
